package main

import (
	"encoding/json"
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"hello/lib/mqttLib"
	"log"
	"time"
)
type DeviceStatus struct {
	GatewayID string `json:"gateway_id"`
	Status string `json:"status"`
}
var que = make(chan string, 10)

func onlineHandler (client mqtt.Client, message mqtt.Message) {
	ds := DeviceStatus{}
	err := json.Unmarshal(message.Payload(), &ds)
	if err != nil {
		log.Printf("unmarshal data error : %s", err.Error())
	}
	que <- ds.GatewayID
}

func main(){
	go func() {
		mqttconfig:= mqttLib.MqttConfig{"tcp://dcharles.work:1883/mqtt", "client_test"}
		c := mqttLib.NewMqttClient(mqttconfig, func(client mqtt.Client, msg mqtt.Message) {
			log.Print(msg)
		})
		if t := c.Connect();t.Wait() && t.Error() != nil {
			log.Println(t.Error())
		}
		// defer c.Disconnect(3*1000)
		if token := c.Subscribe(mqttLib.DeviceOnline, 0, onlineHandler); token.Wait() && token.Error() != nil {
			log.Printf("Error : Publish message error : %s", token.Error().Error())
		}
	}()
	for {
		time.Sleep(time.Second)
		fmt.Println("main")
	}
}